package com.gxz.aspect;

import com.gxz.pojo.User;
import com.gxz.service.LoggerService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@Component
@Aspect
public class MethodInvokeAdvice {
    @Autowired
    private LoggerService loggerService;

    @Pointcut("execution(* com.gxz.service.UserService.*(..))")
    public void pt() {
    }

    @Around("pt()")
    public Object logMethodInvoke(ProceedingJoinPoint joinPoint) {

        Signature signature = joinPoint.getSignature();
        Class declaringType = signature.getDeclaringType();
        String name = signature.getName();
        Object[] args = joinPoint.getArgs();

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);  // 格式化

        String argString = formattedDateTime + "  方法执行" + declaringType + "@" + name;

        for (int i = 0; i < args.length; i++) {
            if (args[i].getClass() == User.class) {
                argString += "【执行参数】"  + args[i].toString();
            } else {
                argString += "【执行参数】"  + args[i];
            }
        }
        System.out.println(argString);
        if(argString.length() >500) {
            argString = argString.substring(0,500);
        }
        loggerService.log(argString);
        try {
            return joinPoint.proceed(args);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    @AfterThrowing(pointcut = "execution(* com.gxz.service.*Service.*(..))", throwing = "err")
    public void logException(Throwable err) {
        System.out.println("异常信息：" + err.getMessage());
    }
}
